import { Injectable } from '@nestjs/common';
import { CreateCustomerDto } from './dto/create-customer.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Customer } from './entities/customer.entity';
import { ResponseService } from 'src/response/response.service';
import { SimplePaginatedResponse } from 'src/common/dto/pagination.dto';

@Injectable()
export class CustomerService {
  constructor(
    @InjectRepository(Customer) private readonly customer: Repository<Customer>,
    private readonly responseService: ResponseService,
  ) {}

  async create(createCustomerDto: CreateCustomerDto) {
    const result = await this.customer.save(createCustomerDto);
    return this.responseService.createSuccessResponse(result);
  }

  findAll() {
    return this.customer.find();
  }

  findOne(id: number) {
    return this.customer.findOne({ where: { id } });
  }

  async searchByKeyword(
    keyword: string,
    page: number = 1,
    limit: number = 50,
  ): Promise<SimplePaginatedResponse<Customer>> {
    const pageNum = Math.max(1, Math.min(page, 2147483647));
    const pageSize = Math.max(1, Math.min(limit, 1000));
    const skip = (pageNum - 1) * pageSize;

    const [data, total] = await this.customer
      .createQueryBuilder('customer')
      .where('customer.customername LIKE :keyword', { keyword: `%${keyword}%` })
      .orWhere('customer.tel LIKE :keyword', { keyword: `%${keyword}%` })
      .orderBy('customer.id', 'DESC')
      .skip(skip)
      .take(pageSize)
      .getManyAndCount();

    return {
      data,
      total,
      page: pageNum,
      limit: pageSize,
    };
  }

  remove(id: number) {
    const result = this.customer.delete(id);
    return this.responseService.createSuccessResponse(result);
  }
}
